require "Common/define"
require "Logic/Config"
require "Common/functions"
---@class ShopManager
ShopManager = {};
local this = ShopManager;

--看板娘状态
ShopManager.LandladyStatus =
{
    JOIN_SHOP = 1,      --进入商城
    BUY_GOODS = 2,      --购买道具
    REFRESH_GOODS = 3,  --刷新道具
    HOVER_SHOP = 4,     --停留x秒后
    SWITCH_PAGE = 5,    --切换页面
    CLICK_EFFECT = 6,   --点击看板娘
    EXIT_SHOP = 7,      --退出
}
this.limitOpenType = {
    playerLimit = 1,
    mapLimit = 2,
    unionLimit = 6,
}
local shopData = {};
local itemData = {};
local equipData = {};
local shopHeadData = {};
local shopgoodsData = {};
local createPlayerTime = nil;

local shopWindowData = {};
local shopBossladyWordsData = {};
local isNewGetHero = false;

function ShopManager.init()
    itemData = G.dataTable["t_item"];
    equipData = dataTable.getDataTable("t_equip");
    shopHeadData = G.dataTable["t_shophead"];
    shopgoodsData = G.dataTable["t_shopgoods"];
    --新添加判断橱窗解锁条件用的表
    shopWindowData = G.dataTable["t_shopwindow"];
    shopBossladyWordsData = G.dataTable["t_shopbossladywords"];
    ShopManager.ShopLandladyStatus = ShopManager.LandladyStatus.EXIT_SHOP
end

--处理接收的商店数据
function ShopManager.resShopData(msg)
    local shop = {};
    local id = tostring(msg.shopId);
    shop["shopId"] = id;
    shop["refreshTimes"] = tostring(msg.refreshTimes);
    shop["nextRefreshTime"] = tostring(msg.nextRefreshTime);
    shop["refreshUp"] = shopHeadData[id].f_RefreshUp;
    shop["refreshConsume"] = decodeJsonStrToTabel(shopHeadData[id].f_RefreshConsume);
    shop["shopItems"] = {};
    local isIgnore; -- 商品是否屏蔽
    local ignoreList; -- 商品屏蔽列表
    --if tonumber(id) == EnumConst.ShopType.heroShop then
    --    isIgnore = true;
    --    ignoreList = {};
    --    for kk, vv in pairs(logicMgr.ActiveManager.getActiveIdListByType(logicMgr.ActiveManager._activityDrawType)) do
    --        local tb_activitydraw = G.dataTable["t_activitydraw"][tostring(vv)]
    --        if tb_activitydraw then
    --            local tb_new_hero = decodeJsonStrToTabel(tb_activitydraw.f_NewHero);
    --            for k, v in pairs(tb_new_hero) do
    --                table.insert(ignoreList, logicMgr.HeroManager.GetHeroStoneIdByModelId(v));
    --            end
    --        end
    --    end
    --end
    local hero = logicMgr.HeroManager.getOwnerHeroList();
    local shopItems = msg.ShopItems;
    for i = 1, #shopItems do
        local item = {};
        local add = true
        local shopItemModelId = tostring(shopItems[i].shopItemModelId); --老字段shop表唯一id，该废弃了
        item.itemModelId = tostring(shopItems[i].itemModelId)  --新字段
        item["shopItemId"] = tostring(shopItems[i].shopItemId);--老字段，该废弃了
        item["shopItemModelId"] = shopItemModelId
        item["window"] = shopItems[i].window;

        local windowId = item["window"] + shop["shopId"];
        local windowData = shopWindowData[tostring(windowId)]
        if windowData ~= nil then
            item["windowCondition"] = decodeJsonStrToTabel(shopWindowData[tostring(windowId)].f_WindowCondition);
        else
            logError("找不到商品橱窗 data:" .."id:".. windowId); --..shopWindowData
        end
        local windowCondition = item["windowCondition"];
        if windowCondition ~= nil and next(windowCondition) ~= nil then
            item["isLock"] = true;
            for i = 1, #hero do
                if tonumber(hero[i].partnerModelId) == tonumber(windowCondition[2]) then
                    item["isLock"] = false;
                    if hero[i].star >= G.dataTable["t_global"][tostring(93)].f_int_value then
                        add = false;
                    end
                    break;
                end
            end
            if add and tonumber(windowCondition[1]) == 4 and (not logicMgr.HeroManager.isHeroFullyOpen(windowCondition[2])) then
                add = false;
            end
        end

        item["remainCount"] = shopItems[i].remainCount;
        local f = shopgoodsData[shopItemModelId]
        if f ~= nil then
            local itemModelId = item.itemModelId--tostring(shopgoodsData[shopItemModelId].f_GoodsID);
            if logicMgr.ItemManager.IsEquip(item.itemModelId) then
                --item["itemModelId"] = itemModelId;
                local e = equipData[itemModelId]
                if e then
                    item["icon"] = e.f_EquipIcon;
                    item["quality"] = e.f_EquipQuality;
                    item["itemType"] = EnumConst.ItemTypeEnum.Equip;
                    item["name"] = getLanguage(e.f_EquipName);
                    item["desc"] = getLanguage(e.f_EquipDesc);
                else
                    logError("can not find equipconfig by id:" .. itemModelId)
                    add = false
                end
            else
                --item["itemModelId"] = itemModelId;
                local it = itemData[itemModelId]
                if it then
                    item["icon"] = it.f_Icon;
                    item["quality"] = it.f_Quality;
                    item["itemType"] = it.f_BagType;
                    item["name"] = getLanguage(it.f_ItemName);
                    item["desc"] = getLanguage(it.f_Desc);
                else
                    logError("can not find itemconfig by id:" .. itemModelId)
                    add = false
                end
            end

            item["num"] = shopgoodsData[shopItemModelId].f_Quantity;
            local price = decodeJsonStrToTabel(shopgoodsData[shopItemModelId].f_Price)[1];
            item["monyType"] = price[1];
            item["moneyIcon"] = itemData[tostring(price[1])].f_Icon;
            item["price"] = price[2];
            item["discount"] = shopgoodsData[shopItemModelId].f_Discount;
            if isIgnore then
                for k, v in pairs(ignoreList) do
                    if v == tonumber(item.itemModelId) then
                        add = false;
                        break;
                    end
                end
            end
            if add then
                table.insert(shop["shopItems"], item);
            end
        else
            logError("找不到商品 id：" .. shopItemModelId)
        end
    end
    if tonumber(shop["shopId"]) == EnumConst.ShopType.heroShop then
        table.sort(shop["shopItems"], function(a, b)
            if a.isLock and b.isLock or not a.isLock and not b.isLock then
                return a.window < b.window;
            else
                return b.isLock == true;
            end
        end);
    else
        table.sort(shop["shopItems"], function(a, b)
            return a.window < b.window;
        end);
    end
    shopData = shop;

    -- printTable("=============================>");
    -- printTable(shopData);
    if ShopManager.ShopLandladyStatus ~= ShopManager.LandladyStatus.REFRESH_GOODS
    and ShopManager.ShopLandladyStatus ~= ShopManager.LandladyStatus.JOIN_SHOP then
        ShopManager.ShopLandladyStatus = ShopManager.LandladyStatus.SWITCH_PAGE
    end
    FireEvent(Config.EventType.Fresh_Shop, Config.EnuRefreshShop.UpdateShopList);
end

function ShopManager.equipBaseInfo(itemData)
    local equip = equipData[tostring(itemData.itemModelId)];
    if equip ~= nil then
        itemData["name"] = getLanguage(equip.f_EquipName);
        itemData["tabType"] = EnumConst.ItemTableEnum.Equip;
        itemData["itemType"] = EnumConst.ItemTypeEnum.Equip;
        itemData["heroType"] = equip.f_EquipHeroType;
        itemData["icon"] = equip.f_EquipIcon;
        itemData["level"] = equip.f_EquipLv;
        itemData["part"] = equip.f_EquipType;
        itemData["partName"] = getLanguage("EquipType" .. equip.f_EquipType);
        itemData["quality"] = equip.f_EquipQuality;
        itemData["suit"] = equip.f_EquipSuit;
        itemData["desc"] = getLanguage(equip.f_EquipDesc);
        itemData["baseAttr"] = equip.f_EquipBasic;
        itemData["attribute"] = {};
        itemData["suitnum"] = 0;
        local attrs = decodeJsonStrToTabel(itemData["baseAttr"]);
        for i = 1, #attrs do
            itemData["attribute"][attrs[i][1]] = attrs[i][2];
        end
        itemData["random"] = {};

        itemData["power"] = logicMgr.HeroManager.processPower(itemData["attribute"], equip.f_EquipHeroType);
    end
    --[[local suitCfg = G.dataTable["t_equipsuit"][tostring(itemData["suit"])];
    if suitCfg ~= nil then
        itemData["suitName"] = getLanguage(suitCfg.f_EquipSuitName);
        itemData["suitValue1"] = suitCfg.f_EquipSuitValue1;
        itemData["suitValue2"] = suitCfg.f_EquipSuitValue2;
        itemData["suitDesc1"] = getLanguage(suitCfg.f_EquipSuitDes1);
        itemData["suitDesc2"] = getLanguage(suitCfg.f_EquipSuitDes2);
    end
    local refineCfg = dataTable.getDataTableByStringId("t_equiprefine",itemData["itemModelId"]);
    if refineCfg ~= nil then

        itemData["consumeExp"] = decodeJsonStrToTabel(refineCfg.f_EquipRefineLevelExp);
        itemData["maxRfLevel"] = refineCfg.f_EquipRefineLevelMax;
        itemData["baseExp"] = decodeJsonStrToTabel(refineCfg.f_EquipBaseExp)
        itemData["consumeGold"] = decodeJsonStrToTabel(refineCfg.f_EquipRefineGoldCo);
        itemData["baseAttrUp"] = {};
        table.insert(itemData["baseAttrUp"], decodeJsonStrToTabel(refineCfg.f_EquipRefineAtk))
        table.insert(itemData["baseAttrUp"], decodeJsonStrToTabel(refineCfg.f_EquipRefineDef))
        table.insert(itemData["baseAttrUp"], decodeJsonStrToTabel(refineCfg.f_EquipRefineHP))
        for i = 4, 100 do
            local value = refineCfg["f_EquipRefine" .. i]
            if not value then
                break
            end
            local attrs = decodeJsonStrToTabel(value)
            if attrs[1] > 0 then
                itemData["baseAttrUp"][i] = attrs
            end
        end
    end]]
    return itemData;
end

--刷新次数返回
function ShopManager.refreshShopData(msg)
    if shopData["shopId"] ~= nil and shopData["shopId"] == tostring(msg.shopId) then
        shopData["refreshTimes"] = tostring(msg.times);
        local _refreshDic = {}
        _refreshDic.shop_id = shopData["shopId"]
        _refreshDic.refresh_times = shopData["refreshTimes"]
        TAManager.TrackByDictionary("shop_reset", _refreshDic)
    end
    ShopManager.ShopLandladyStatus = ShopManager.LandladyStatus.REFRESH_GOODS
    FireEvent(Config.EventType.Fresh_Shop, Config.EnuRefreshShop.UpdateTimes);
end

--刷新时间返回
function ShopManager.refreshShopTime(msg)
    if shopData ~= nil then
        shopData["nextRefreshTime"] = tostring(msg.time);
    end
    FireEvent(Config.EventType.Fresh_Shop, Config.EnuRefreshShop.UpdateTime);
end

--刷新购买返回
function ShopManager.refreshShopBuyItem(msg)
    if shopData["shopId"] ~= nil and shopData["shopId"] == tostring(msg.shopId) then
        --local buyItemData = {};
        --buyItemData["shopId"] = msg.shopId;
        --buyItemData["shopItemId"] = tostring(msg.shopItemId);
        --buyItemData["shopItemModelId"] = msg.shopItemModelId;
        --buyItemData["itemModelId"] = msg.itemModelId;
        --buyItemData["monyType"] = msg.monyType;
        --buyItemData["num"] = msg.num;
        
        local showNum = 1
        for k, v in pairs(shopData["shopItems"]) do
            if v["shopItemId"] == tostring(msg.shopItemId) then
                local num = v["remainCount"] - msg.num;
                v["remainCount"] = num;

                showNum = v["num"]

                local _shopDic = {}
                _shopDic.shop_id = tostring(msg.shopId)                         --EnumConst.ShopType 枚举值
                _shopDic.shop_buy_count = tonumber(msg.num)                     --商店购买物品的数量
                _shopDic.shop_buy_price = tonumber(v.price)                     --商店购买的单价，t_shopgoods.f_Price
                _shopDic.shop_buy_cost = tonumber(msg.num) *tonumber(v.price)   --商店购买的总花费
                _shopDic.shop_money_type = tostring(msg.monyType)               --使用的货币类型
                _shopDic.shop_item_id = tostring(msg.itemModelId)               -- t_item 表id
                _shopDic.shop_commodity_id = tostring(msg.shopItemModelId)      -- t_shopgoods 表id
                _shopDic.shop_window_id = tostring(v["window"]) or "-1"         --窗口id

                -- _shopDic.shop_window_id = tostring(v["window"])
                -- _shopDic.cargo_ku_id = tostring(msg.shopItemId)
                -- _shopDic.commodity_id = tostring(msg.shopItemModelId)
                -- _shopDic.get_commodity_number = tonumber(msg.num)
                -- _shopDic.get_item_id = tostring(msg.itemModelId)
                -- _shopDic.get_item_number = tonumber(msg.num)
                -- _shopDic.cost_item_id = tostring(msg.monyType)
                -- _shopDic.cost_item_number = tonumber(v.price)
                -- _shopDic.get_consumption_points = logicMgr.ItemManager.GetItemConsumptionPoints(tonumber(msg.monyType)) * tonumber(v.price);
                TAManager.TrackByDictionary("shop_buy",_shopDic)
                break ;
            end
        end
        showNum = msg.num * showNum

        -- 奖励弹窗
        if toNumber(shopData["shopId"]) ~= EnumConst.ShopType.drawing then
            local itemConfigData = G.dataTable["t_item"][tostring(msg.itemModelId)];
            if itemConfigData.f_BagType == EnumConst.ItemTypeEnum.HeroEntity then
                local fHeroInfo = {}
                for k,v in pairs(G.dataTable["t_drop"]) do
                    if tonumber(msg.itemModelId) == tonumber(v.f_DropPoolId) then
                        fHeroInfo = decodeJsonStrToTabel(v.f_Hero);
                    end
                end
                if ShopManager.returnIsNewGetHero() then    --判断是否新获得的英雄
                    if fHeroInfo ~= nil then
                        showUI(PanelNames.UIDrawAnimation, fHeroInfo[1][1], nil, false, function()
                            closeUI(PanelNames.UIDrawAnimation);
                        end, nil, true, true);
                    end
                else    --已拥有，转为碎片
                    local item = {}
                    local tabItems = {}
                    item["itemModelId"] = msg.itemModelId
                    local heroRankId = fHeroInfo[1][1]*1000 + fHeroInfo[1][2]
                    item["num"] = tonumber(G.dataTable["t_herorank"][tostring(heroRankId)].f_RepeatCount or 1)
                    tabItems[msg.itemModelId] = item
                    showUI(PanelNames.UICommonItemGet,nil,nil,3,tabItems,nil,nil,nil,nil,nil,true)
                end
            else
                showUI(PanelNames.UICommonItemGet, msg.itemModelId, showNum, false);
            end
        end
    end
    ShopManager.ShopLandladyStatus = ShopManager.LandladyStatus.BUY_GOODS
    FireEvent(Config.EventType.Fresh_Shop, Config.EnuRefreshShop.UpdateOneShop);
end

--返回当前商店数据
function ShopManager.returnShopData()
    if shopData ~= nil then
        return shopData;
    else
        return nil;
    end
end

--返回当前商店列表
function ShopManager.returnShopList()
    local data = {};
    local openLimitList = {};
    openLimitList[this.limitOpenType.playerLimit] = logicMgr.HeroManager.GetRoleLevel();
    openLimitList[this.limitOpenType.mapLimit] = logicMgr.MapManager.getMapId();
    openLimitList[this.limitOpenType.unionLimit] = logicMgr.GuildManager.getUnionLv();
    local dataTable = G.dataTable["t_shophead"];
    for k, v in pairs(dataTable) do
        local limitCondition = decodeJsonStrToTabel(v.f_UnlockCondition);
        local limitType = limitCondition[1][1];
        local limitLevel = limitCondition[1][2];
        if v.f_Entrance == 0 and openLimitList[limitType] ~= nil and openLimitList[limitType] >= limitLevel then
            table.insert(data, v);
        end
    end
    return data;
end

--设置商店刷新埋点数据
function ShopManager.setRefreshTAData(data)
    this.refreshTAData = data;
end

--返回当前商店看板娘话
function ShopManager.returnShopDialogText()
    local data = ShopManager.returnShopData();
    if data == nil then
        return "";
    end
    local headInfo = shopHeadData[tostring(data.shopId)];
    local wordsCondition = decodeJsonStrToTabel(headInfo.f_WordsCondition);
    local conditionList = {};
    conditionList[1] = logicMgr.HeroManager.GetRoleLevel();
    conditionList[2] = logicMgr.MapManager.getMapId();
    conditionList[5] = logicMgr.MythicDungeonsManager.getMaxLayer()
    local index;
    for i = #wordsCondition, 1, -1 do
        if conditionList[wordsCondition[i][1]] >= wordsCondition[i][2] then
            index = decodeJsonStrToTabel(headInfo.f_BossLadyWords)[i];
            break ;
        end
    end
    if index == nil then
        return "";
    end
    local wordsList = decodeJsonStrToTabel(shopBossladyWordsData[tostring(index)].f_BossLadyWordsLibrary);
    index = ShopManager.randomByList(wordsList);
    if index == nil then
        return "";
    end
    return getLanguage(wordsList[index][1]);
end

function ShopManager.randomByList(list)
    if list == nil or next(list) == nil then
        return nil;
    end
    local sum = 0;
    for k, v in pairs(list) do
        sum = sum + v[2];
    end
    math.randomseed(os.time());
    local n = math.random(sum);
    sum = 0;
    for k, v in pairs(list) do
        sum = sum + v[2];
        if sum >= n then
            return k;
        end
    end
    return #list;
end

--返回当前商店货币
function ShopManager.returnShopGold(shopId)
    local tabGoldData = {};
    local cfg = shopHeadData[tostring(shopId)]
    if cfg == nil then
        return tabGoldData
    end
    local shopGoldData = decodeJsonStrToTabel(shopHeadData[tostring(shopId)].f_Currency);
    for i = 1, #shopGoldData do
        local data = {};
        data["currencyId"] = tostring(shopGoldData[i]);
        data["currencyIcon"] = logicMgr.ItemManager.GetItemIcon(shopGoldData[i])
        table.insert(tabGoldData, data);
    end
    return tabGoldData;
end

---废弃, 创角时间
function ShopManager.AddCreateCharactorTime(createTime)
    createPlayerTime = createTime;
end
--- 废弃, 改用 logicMgr.HeroManager.GetRoleInfo().createTime
function ShopManager.returnCreateCharactorTime()
    return createPlayerTime;
end

function  ShopManager.setIsNewGetHero(buyItem)
    isNewGetHero = false
    local itemConfigData = G.dataTable["t_item"][tostring(buyItem.itemModelId)];
    if itemConfigData.f_BagType == EnumConst.ItemTypeEnum.HeroEntity then
        for k,v in pairs(G.dataTable["t_drop"]) do
            if tonumber(buyItem.itemModelId) == tonumber(v.f_DropPoolId) then
                local fHeroInfo = decodeJsonStrToTabel(v.f_Hero);
                if HeroManager.NotHaveByModeId(fHeroInfo[1][1]) then    --判断是否新获得的英雄
                    isNewGetHero = true
                end
            end
        end
    end
end

function ShopManager.returnIsNewGetHero()
    return isNewGetHero;
end

return ShopManager

